import sys
import uuid
from django.shortcuts import render, redirect
from django.core.mail import send_mail
from django.contrib.auth import (
    authenticate,
    login as auth_login,
    logout as auth_logout,
)

from .models import Token


def send_login_email(request):
    email = request.POST['email']
    uid = str(uuid.uuid4())
    Token.objects.create(email=email, uid=uid)
    print('saving uid', uid, 'for email', email, file=sys.stderr)
    url = request.build_absolute_uri(f'/accounts/login?uid={uid}')
    send_mail(
        'Your login link for TDD',  # 邮件主题
        f'Use this link to log in:\n\n{url}', # 信息
        'tdd@163.com', # 发送方
        [email],  # 接收方列表
    )
    return render(request, 'login_email_sent.html')


from django.contrib.sessions.backends.db import SessionStore
def login(request):
    # print(request.session)
    print('login view', file=sys.stderr)
    uid = request.GET.get('uid')
    # authenticate函数认证uuid是否有效，如果有效返回User对象
    # 否则返回None
    # 使用自定制认证后端(需要在settings.py文件中配置，authenticate函数会调用)
    user = authenticate(uid=uid)
    if user is not None:
        print('log user in')
        auth_login(request, user)
    return redirect('/')


def logout(request):
    auth_logout(request)
    return redirect('/')
